package com.hmall.search.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.hmall.common.utils.CollUtils;
import com.hmall.search.domain.dto.ItemDoc;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: suren@517na.com
 * @CreateTime: 2025-04-07
 * @Description: 查询Service实现类
 */

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<ItemDoc> queryItemByIds(List<Long> ids) {
        if (CollUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }

        List<ItemDoc> itemDocs = new ArrayList<>();
        GetRequest getRequest = new GetRequest("items");
        for (Long id : ids) {
            try {
                GetResponse response = restHighLevelClient.get(getRequest.id(String.valueOf(id)), RequestOptions.DEFAULT);
                if (StringUtils.isNotBlank(response.getSourceAsString())) {
                    itemDocs.add(JSONUtil.toBean(response.getSourceAsString(), ItemDoc.class));
                }
            } catch (IOException e) {
                log.error("查询商品{}出错", id);
            }

        }
        return itemDocs;
    }

    @Override
    public ItemDoc queryItemById(Long id) {
        GetRequest getRequest = new GetRequest("items").id(String.valueOf(id));
        try {
            GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            return JSONUtil.toBean(response.getSourceAsString(), ItemDoc.class);
        } catch (IOException e) {
            log.error("查询商品{}出错", id);
            return null;
        }
    }
}
